package com.xiaolun;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Author 硕鼠
 * @Date 2020/4/16 11:13
 * @Version 1.0
 * @Description 加密
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean //实类
    PasswordEncoder passwordEncoder() {  //对密码加密
        // @Autowired 注入并使用 PasswordEncoder 接口的实例，然后调用其 matches 方法去匹配原密码和数据库中保存的“密码”
        return NoOpPasswordEncoder.getInstance(); //无密码编码器，不加密
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication() //内存中，代码里面配置登录和密码
                .withUser("xiaolun")
                .password("123456")
                .roles("admin"); //配置角色
//                .and()   //使用and()配置很多个，可以看作结束标签
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
       web.ignoring().antMatchers("/js/**","/css/**","/image/**");//不要拦截该文件
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()  //所有请求都要经过认证
                .and()
                .formLogin()
                .loginPage("/login.html")  //登录页面（登录接口）
                .loginProcessingUrl("/doLogin") //配置登录接口
                .successForwardUrl("/success")//默认成功跳转地址（服务端跳转）不管从什么页面来，登录成功之后都是到该页面
//                .defaultSuccessUrl("/s")//重定向（从哪里来到哪里去）
//                .failureForwardUrl()
                .permitAll()
                .and()
                .logout()
//                .logoutUrl("logout")
                .logoutSuccessUrl("/login.html")//注销成功去的页面
                .and()
                .csrf().disable(); //为了防止跨站提交攻击，通常会配置csrf
    }
}
